package com.tuozixuan.onesql.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.google.common.base.Functions;
import com.google.common.collect.Maps;

public enum LocalDataSource {

	INSTANCE;
	
	//private List<ConnectionInfo> connectionInfoList;
	
	private Map<String, ConnectionInfo> connectionInfoMap = Maps.newHashMap();
	
	private Map<String, BasicDataSource> dataSourceMap = Maps.newHashMap();
	
	public void init(List<ConnectionInfo> connectionInfoList){
		//this.connectionInfoList = connectionInfoList;
		connectionInfoMap = connectionInfoList.stream().collect(Collectors.toMap(ConnectionInfo::getName, Functions.identity()));
    }
	
	public DataSource getDataSource(String connectionName) {
		BasicDataSource basicDataSource = dataSourceMap.get(connectionName);
		if (Objects.isNull(basicDataSource)) {
			ConnectionInfo connectionInfo = connectionInfoMap.get(connectionName);
			basicDataSource = this.initDataSource(connectionInfo);
			dataSourceMap.put(connectionName, basicDataSource);
		}
		
        return basicDataSource;
    }
    
    public Connection getConnection(String connectionName) throws SQLException {
        return getDataSource(connectionName).getConnection();
    }
	
	private BasicDataSource initDataSource(ConnectionInfo connectionInfo){
		BasicDataSource datasource = new BasicDataSource();
        //数据库连接信息,必须的
        datasource.setDriverClassName("com.mysql.jdbc.Driver");
        datasource.setUrl(String.format("jdbc:mysql://%s:%s/", connectionInfo.getHost(), connectionInfo.getPort()));
        datasource.setUsername(connectionInfo.getUserName());
        datasource.setPassword(connectionInfo.getPassword());
        //对象连接池中的连接数量配置,可选的
        datasource.setInitialSize(10);//初始化的连接数
        datasource.setMaxActive(8);//最大连接数量
        datasource.setMaxIdle(5);//最大空闲数
        datasource.setMinIdle(1);//最小空闲
        return datasource;
    }
}
